import queryStringify from './queryStringify'

/**
 * 历史访问页面操作
 * */
export default {
    get() {
        try {
            const page = wx.getStorageSync('HISTORY_PAGE')
            return page.url
        } catch (e) {
            return null
        }
    },
    set({name = '', url = '', params = null}) {
        if (params) {
            if (url.includes('?')) {
                url += queryStringify(params)
            } else {
                url += `?${queryStringify(params)}`
            }
        }
        wx.setStorageSync('HISTORY_PAGE', {
            url,
            name
        })
    },
    clear() {
        const page = wx.getStorageSync('HISTORY_PAGE')
        if (page) {
            wx.removeStorageSync('HISTORY_PAGE')
        }
    },
    route(type) {
        const url = this.get()
        if (url) {
            if (type && type === 'push') {
                wx.navigateTo({
                    url,
                    fail: e => {
                        console.error('页面跳转失败', e)
                    }
                })
            } else {
                wx.reLaunch({
                    url,
                    fail: e => {
                        console.error('页面跳转失败', e)
                    }
                })
            }
        } else {
            console.log('不存在历史访问，不跳转')
        }
    }
}
